package com.linkai.序列化;

import java.io.*;

/**
 * @Description: 可选的自定义序列化 transient关键字
 * @Author: 林凯
 * @Date: 2021/10/22 0:00
 */
public class Test03 {

    public static void WriteObject() {
        try {
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("student.txt"));
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream("student.txt"));

            // 序列化 student
            Student student = new Student("JackLin", 21, 178, true);
            oos.writeObject(student);
            System.out.println("序列化之前");
            System.out.println(student);
            Student student1 = (Student) ois.readObject();
            System.out.println("序列化之后");
            System.out.println(student1);

            /*
                结论：使用transient修饰的属性，java序列化时，会忽略掉此字段，所以反序列化出的对象，被transient修饰的属性是默认值。
                      对于引用类型，值是null；基本类型，值是0；boolean类型，值是false。
            * */

        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        WriteObject();
    }

}

class Student implements Serializable {

    // transient 关键字，不需要序列化名字与年龄
    private transient String name;
    private transient int age;
    private transient boolean singlehood;
    private int height;


    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", height=" + height +
                ", singlehood=" + singlehood +
                '}';
    }

    public Student() {
    }

    public Student(String name, int age, int height, boolean singlehood) {
        this.name = name;
        this.age = age;
        this.height = height;
        this.singlehood = singlehood;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public int getHeight() {
        return height;
    }

    public void setHeight(int height) {
        this.height = height;
    }

    public boolean isSinglehood() {
        return singlehood;
    }

    public void setSinglehood(boolean singlehood) {
        this.singlehood = singlehood;
    }
}
